package org.dromara.common.mybatis.core.page;


import cn.hutool.core.collection.CollUtil;
import lombok.Data;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.Serial;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class CustomConditions extends PageQuery {

    @Serial
    private static final long serialVersionUID = -8759204993553239827L;

    public CustomConditions(List<Condition> filters) {
        this.filters = filters;
    }

    public CustomConditions() {
    }

    /**
     * 自定义条件
     */
    private List<Condition> filters;

    public List<Condition> getFilters() {
        return filters;
    }

    public Condition getFilters(String column) {
        List<Condition> list = filters.stream().filter(e -> StringUtils.equals(e.getColumn(), column)).collect(Collectors.toList());
        return CollUtil.isEmpty(list) ? null : list.get(0);
    }

    @Data
    public static class Condition {


        public Condition() {
        }

        public Condition(String column, String action, String value) {
            this.action = action;
            this.column = column;
            this.value = value;
        }

        public Condition(String column, String action, String... value) {
            this.action = action;
            this.column = column;
            this.setValue(value);
        }

        public Condition(String column, String action, Collection<String> value) {
            this.action = action;
            this.column = column;
            this.setValue(value);
        }

        /**
         * 类型,==,!=,>,<,>=,<=,like,in,notIn,betweeen,isNull,isNotNull
         */
        private String action;
        /**
         * 字段
         */
        private String column;
        /**
         * 值
         */
        private String value;


        /**
         * http 前台请求使用
         *
         * @param value
         */
        public void setValue(String value) {
            this.value = value;
        }

        /**
         * 过滤器拦截，不支持http前台请求
         *
         * @param value
         */
        public void setValue(String... value) {
            if (ObjectUtils.isNotEmpty(value)) {
                this.value = String.join(",", Arrays.stream(value).filter(i -> !i.isEmpty()).collect(Collectors.toList()));
            } else {
                this.value = "";
            }
        }

        /**
         * 过滤器拦截，不支持http前台请求
         *
         * @param value
         */
        public void setValue(Collection<String> value) {
            if (ObjectUtils.isNotEmpty(value)) {
                this.setValue(value.toArray(new String[value.size()]));
            } else {
                this.value = "";
            }
        }
    }
}
